Page({
  data: {
    consultantLevels: [],
    consultationCategories: [],
    selectedLevelId: '',
    selectedCategoryId: '',
    appointmentTime: '',
    description: '',
    consultants: []
  },

  onLoad: function(options) {
    this.checkLoginStatus();
    this.fetchConsultantLevels();
    this.fetchConsultationCategories();
    
    // 如果有传入的参数,则设置并搜索
    if (options.levelId || options.categoryId || options.appointmentTime) {
      console.log(options);
      this.setData({
        selectedLevelId: options.levelId || '',
        selectedCategoryId: options.categoryId || '',
        appointmentTime: options.appointmentTime || ''
      });
      this.searchConsultants();
    }
  },

  checkLoginStatus: function() {
    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，请先登录',
        showCancel: false,
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    }
  },

  fetchConsultantLevels: function() {
    wx.request({
      url: 'http://localhost:8080/api/teacherLevels',
      success: (res) => {
        this.setData({
          consultantLevels: res.data
        });
      },
      fail: (err) => {
        console.error('获取咨询师等级失败:', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    });
  },

  fetchConsultationCategories: function() {
    wx.request({
      url: 'http://localhost:8080/api/goods',
      success: (res) => {
        this.setData({
          consultationCategories: res.data
        });
      },
      fail: (err) => {
        console.error('获取咨询类别失败:', err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      }
    });
  },

  searchConsultants: function() {
    if (!this.data.selectedLevelId || !this.data.selectedCategoryId || !this.data.appointmentTime) {
      return; // 如果没有选择完整信息,不进行搜索
    }

    const selectedLevel = this.data.consultantLevels.find(level => level.id.toString() === this.data.selectedLevelId);
    const selectedCategory = this.data.consultationCategories.find(category => category.id.toString() === this.data.selectedCategoryId);

    wx.request({
      url: 'http://localhost:8080/api/consultants/search',
      data: {
        teacherGradeName: selectedLevel ? selectedLevel.name : '',
        fieldName: selectedCategory ? selectedCategory.name : '',
        appointmentTime: this.data.appointmentTime
      },
      success: (res) => {
        console.log(res);
        this.setData({
          consultants: res.data.consultants
        });
      },
      fail: (err) => {
        console.error('搜索咨询师失败:', err);
        wx.showToast({
          title: '搜索失败',
          icon: 'none'
        });
      }
    });
  },

  onLevelChange: function(e) {
    this.setData({
      selectedLevelId: e.detail.value
    });
    this.searchConsultants();
  },

  onCategoryChange: function(e) {
    this.setData({
      selectedCategoryId: e.detail.value
    });
    this.searchConsultants();
  },

  onDateChange: function(e) {
    this.setData({
      appointmentTime: e.detail.value
    });
    this.searchConsultants();
  },

  onDescriptionInput: function(e) {
    this.setData({
      description: e.detail.value
    });
  },

  onCancel: function() {
    wx.navigateBack();
  },

  onConfirm: function() {
    if (!this.data.selectedLevelId || !this.data.selectedCategoryId || !this.data.appointmentTime) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
  
    const selectedLevel = this.data.consultantLevels.find(level => level.id.toString() === this.data.selectedLevelId);
    const selectedCategory = this.data.consultationCategories.find(category => category.id.toString() === this.data.selectedCategoryId);
  
    console.log(selectedLevel);

    // 构建查询参数
    const queryParams = {
      levelName: selectedLevel ? encodeURIComponent(selectedLevel.name) : '',
      categoryName: selectedCategory ? encodeURIComponent(selectedCategory.name) : '',
      appointmentTime: encodeURIComponent(this.data.appointmentTime)
    };

    // console.log(q);
  
    // 跳转到 appointmentSearch 页面，并传递查询参数
    wx.navigateTo({
      url: `/pages/index/appointment/aappointmentSearch/appointmentSearch?levelName=${queryParams.levelName}&categoryName=${queryParams.categoryName}&appointmentTime=${queryParams.appointmentTime}`
    });
  }
});